﻿Imports TBCC.UtilityMobile
Imports System.Text.RegularExpressions

Public Class StartupViewForm

    Private _isOnline As Boolean
    Private _pi As ProjectItem
    Private _il As IList(Of StartUpTypeItem) = New List(Of StartUpTypeItem)
    Private _sts As StartUpTypeService
    Private _lastTime As DateTime
    Private _isModify As Boolean
    Private _activeType As Integer '0:所有终端; 1:终端;

#Region " 构造函数 "

    Public Sub New()

        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        _activeType = 0
        Me.dgvStartup.AutoGenerateColumns = False

        Me.tsbInsert.Enabled = False
        Me.tsmiInsert.Enabled = False
    End Sub

    Public Sub New(ByVal pi As ProjectItem, ByVal isOnline As Boolean)

        ' 此调用是 Windows 窗体设计器所必需的。
        Me.New()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        _activeType = 1
        Me.scMain.Panel1.Enabled = False
        Me.scMain.Panel1Collapsed = True
        Me.Size = New Size(Me.Width - Me.scMain.SplitterDistance, Me.Height)

        If pi IsNot Nothing Then
            _sts = New StartUpTypeService(pi)
        End If
        _pi = pi
        _isOnline = isOnline

        If _isOnline = True Then
            Me.tsbInsert.Enabled = False
            Me.tsbEdit.Enabled = False
            Me.tsbDelete.Enabled = False
            Me.tsbSave.Enabled = False
            'Me.tsbDetail.Enabled = False
            Me.tsmiInsert.Enabled = False
            Me.tsmiEdit.Enabled = False
            Me.tsmiDelete.Enabled = False
            'Me.tsmiDetail.Enabled = False
        Else

        End If

        If _pi IsNot Nothing Then
            Me.Text &= String.Format(" [终端:{0}]", _pi.ProjectName)
        Else
            Me.Text &= " [终端:未知]"
        End If

    End Sub

#End Region

    Private Sub StartupDetailAddForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.CenterToParent()

        Me.dtpBeginTime.Value = New DateTime(Now.Year, Now.Month, Now.Day)
        Me.dtpEndTime.Value = Me.dtpBeginTime.Value.AddDays(1)

        Select Case _activeType
            Case 0
                LoadProjectList(String.Empty)

            Case 1
                'LoadData()

        End Select
    End Sub

    Private Sub StartupViewForm_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
        If Asc(e.KeyChar) = Keys.Escape Then
            Me.Close()
        End If
    End Sub

    Private Sub StartupDetailViewForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If _isModify = True Then
            Select Case msg.ShowYesNoCancel("启停记录已经修改，是否需要保存？")
                Case Windows.Forms.DialogResult.Yes
                    tsbSave_Click(sender, e)

                Case Windows.Forms.DialogResult.Cancel
                    e.Cancel = True

            End Select
        End If
    End Sub

    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click

        Search()

    End Sub

    Private Sub LoadProjectList(ByVal pattern As String)

        Me.tvPrjList.Nodes.Clear()

        If MainForm.ProjectList IsNot Nothing Then
            For Each row As DataGridViewRow In MainForm.ProjectList.Values
                Dim pi As ProjectItem
                pi = row.Tag
                If pi IsNot Nothing Then
                    Try
                        If pi.ProjectName.IndexOf(pattern) >= 0 Then
                            Dim node As New TreeNode()
                            node.Name = pi.ProjectMacID
                            node.Text = pi.ProjectName
                            node.Tag = pi
                            Me.tvPrjList.Nodes.Add(node)
                        End If
                    Catch ex As Exception
                        Debug.WriteLine(ex.Message)
                    End Try
                End If
            Next
        End If

    End Sub

    Private Sub LoadData()
        If _isOnline = True Then
            LoadData_Online()
        Else
            LoadData_Offline()
        End If
    End Sub

    Private Sub LoadData_Online()



        'For i As Integer = 0 To 4
        '    Dim sti As New StartUpTypeItem()
        '    sti.SeqNo = i + 1
        '    sti.BeginTime = DateTime.Now.AddDays(-1)
        '    sti.EndTime = DateTime.Now.AddHours(i)
        '    _il.Add(sti)
        'Next
        'Me.bsStartup.DataSource = _il
    End Sub

    Private Sub LoadData_Offline()

        If _sts IsNot Nothing Then
            _il = _sts.GetStartUpGroupList(False)

            'For i As Integer = 0 To 4
            '    Dim sti As New StartUpTypeItem()
            '    sti.SeqNo = i + 1
            '    sti.BeginTime = DateTime.Now.AddDays(-1)
            '    sti.EndTime = DateTime.Now.AddHours(i)
            '    _il.Add(sti)
            'Next

            Me.bsStartup.DataSource = _il

            If _il IsNot Nothing AndAlso _il.Count > 0 Then
                _lastTime = _il.Item(_il.Count - 1).EndTime
            Else
                _lastTime = New DateTime(Now.Year, Now.Month, Now.Day)
            End If
        Else
            _lastTime = New DateTime(Now.Year, Now.Month, Now.Day)
        End If

    End Sub

    Private Sub Search()

        If _sts IsNot Nothing Then
            Dim beginTime, endTime As DateTime
            Dim beginAddr, endAddr, shipper, carrier, receiver As String
            beginTime = Nothing : endTime = Nothing
            beginAddr = Nothing : endAddr = Nothing : shipper = Nothing : carrier = Nothing : receiver = Nothing

            If Me.chkDateTime.Checked = True Then
                beginTime = Me.dtpBeginTime.Value
                endTime = Me.dtpEndTime.Value
            End If

            If Me.txtBeginAddr.TextLength > 0 Then
                beginAddr = Me.txtBeginAddr.Text
            End If

            If Me.txtEndAddr.TextLength > 0 Then
                endAddr = Me.txtEndAddr.Text
            End If

            If Me.txtShipper.TextLength > 0 Then
                shipper = Me.txtShipper.Text
            End If

            If Me.txtCarrier.TextLength > 0 Then
                carrier = Me.txtCarrier.Text
            End If

            If Me.txtReceiver.TextLength > 0 Then
                receiver = Me.txtReceiver.Text
            End If

            _il = _sts.GetStartUpGroupList(beginTime, endTime, beginAddr, endAddr, shipper, carrier, receiver, False)

            Me.bsStartup.DataSource = _il

            If _il IsNot Nothing AndAlso _il.Count > 0 Then
                _lastTime = _il.Item(_il.Count - 1).EndTime
            Else
                _lastTime = New DateTime(Now.Year, Now.Month, Now.Day)
            End If
        Else
            _lastTime = New DateTime(Now.Year, Now.Month, Now.Day)
        End If

    End Sub

    Private Sub chkDateTime_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkDateTime.CheckedChanged
        Me.pnlDateTime.Enabled = Me.chkDateTime.Checked
    End Sub

    Private Sub dtpBeginTime_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpBeginTime.ValueChanged
        Me.dtpEndTime.MinDate = Me.dtpBeginTime.Value
    End Sub

    Private Sub tvPrjList_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles tvPrjList.AfterSelect
        If Me.tvPrjList.SelectedNode IsNot Nothing Then
            _pi = Me.tvPrjList.SelectedNode.Tag
            If _pi IsNot Nothing Then
                _sts = New StartUpTypeService(_pi)
            Else
                _sts = Nothing
            End If
        Else
            _sts = Nothing
        End If
    End Sub

    Private Sub txtPrjName_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPrjName.TextChanged

        LoadProjectList(Me.txtPrjName.Text)

    End Sub

#Region " DataGridView消息处理 "

    Private Sub dgvStartup_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles dgvStartup.DataError
        e.Cancel = True
    End Sub

    Private Sub dgvStartup_UserAddedRow(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) Handles dgvStartup.UserAddedRow
        e.Row.Cells(0).Value = e.Row.Index + 1
    End Sub

#End Region

#Region " 工具栏操作 "

    Private Sub tsbInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbInsert.Click, tsmiInsert.Click

        If _isOnline = False Then
            'Insert()
        End If

    End Sub

    Private Sub tsbDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbDelete.Click, tsmiDelete.Click

        If _isOnline = False Then
            Delete()
        End If

    End Sub

    Private Sub tsbEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbEdit.Click, tsmiEdit.Click

        If _isOnline = False Then
            Edit()
        End If

    End Sub

    Private Sub tsbSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbSave.Click

        If _isOnline = False Then
            If Save() = True Then
                _isModify = False
                msg.Show("保存成功。")
            Else
                msg.ShowError("保存失败。")
            End If
        End If

    End Sub

    Private Sub tsbDetail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbDetail.Click, dgvStartup.DoubleClick

        Detail()

    End Sub

    Private Sub tsbHisData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbHisData.Click, tsmiHisData.Click

        HistoryData()

    End Sub

    Private Sub Insert()
        Dim sti As New StartUpTypeItem()
        sti.BeginTime = _lastTime
        sti.EndTime = _lastTime
        Dim frm As New StartupItemForm(ActiveType.Create, sti)
        If frm.ShowDialog = Windows.Forms.DialogResult.OK Then
            _HH.Create(frm.STI)
            frm.STI.SeqNo = Me.bsStartup.Count + 1
            Dim index As Integer = -1
            For i As Integer = 0 To Me.bsStartup.Count - 1
                If Me.bsStartup.Item(i).BeginTime > frm.STI.BeginTime Then
                    index = i
                    Exit For
                End If
            Next
            If index <> -1 Then
                Me.bsStartup.Insert(index, frm.STI)
                ReloadSeqNo()
            Else
                _lastTime = frm.STI.EndTime
                Me.bsStartup.Add(frm.STI)
            End If
            _isModify = True
        End If
    End Sub

    Private Sub Delete()
        If Me.bsStartup.Current IsNot Nothing Then
            If msg.ShowYesNo("是否确定要删除该记录及相关历史数据？") = Windows.Forms.DialogResult.Yes Then
                _HH.Delete(Me.bsStartup.Current)
                If Me.bsStartup.IndexOf(Me.bsStartup.Current) = Me.bsStartup.Count - 1 AndAlso Me.bsStartup.Count > 1 Then
                    _lastTime = Me.bsStartup.Item(Me.bsStartup.Count - 2).EndTime
                End If
                Me.bsStartup.RemoveCurrent()
                Me.ReloadSeqNo()
                _isModify = True
            End If
        End If
    End Sub

    Private Sub Edit()
        Dim sti As StartUpTypeItem
        sti = Me.bsStartup.Current

        If sti IsNot Nothing Then
            Dim frm As New StartupItemForm(ActiveType.Modify, sti)
            If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
                _HH.Modify(sti)
                If sti.SeqNo = Me.bsStartup.Count Then 'LastItem
                    _lastTime = frm.STI.EndTime
                End If
                _isModify = True
            End If
        End If
    End Sub

    Private Function Save() As Boolean

        If _sts IsNot Nothing Then

            For Each hhi As HistoryHandleItem(Of StartUpTypeItem) In _HH.List
                Select Case hhi.HandleType
                    Case HandleType.Create
                        _sts.InsertStartUpTypeItem(hhi.HandleObject)

                    Case HandleType.Modify
                        _sts.UpdateStartUpTypeItem(hhi.HandleObject)

                    Case HandleType.Delete
                        _sts.DeleteStartUpTypeItem(hhi.HandleObject)

                End Select
            Next

            _HH.Clear()
            'Return _sts.UpdateStartUpDetailGroupList(_il)
            Return True
        End If

        Return False
    End Function

    Private Sub ReloadSeqNo()
        For i As Integer = 0 To Me.bsStartup.Count - 1
            Me.bsStartup.Item(i).SeqNo = i + 1
        Next
    End Sub

    Private Sub Detail()
        If Me.bsStartup.Current IsNot Nothing Then
            Dim frm As New StartupDetailViewForm(Of StartUpDetailTypeItem, StartUpTypeItem)(_pi, Me.bsStartup.Current)
            frm.ShowDialog()
        End If
    End Sub

    Private Sub HistoryData()
        If Me.bsStartup.Current IsNot Nothing Then
            Dim sti As StartUpTypeItem = Me.bsStartup.Current
            Dim frm As New HDViewForm(_pi, sti)
            frm.Show(Me)
        End If
    End Sub

#End Region

#Region " 历史操作列表 "

    Private _HH As New HistoryHandler(Of StartUpTypeItem)

    Private Class HistoryHandler(Of T)

        Private _HistoryList As IList(Of HistoryHandleItem(Of T)) = New List(Of HistoryHandleItem(Of T))
        Public ReadOnly Property List() As IList(Of HistoryHandleItem(Of T))
            Get
                Return _HistoryList
            End Get
        End Property

        Public Sub Create(ByVal obj As T)
            AddHandle(obj, HandleType.Create)
        End Sub

        Public Sub Modify(ByVal obj As T)
            Dim index As Integer = -1
            Dim hhi As HistoryHandleItem(Of T)
            For i As Integer = 0 To _HistoryList.Count - 1
                hhi = _HistoryList(i)
                If (hhi.HandleType = HandleType.Create OrElse hhi.HandleType = HandleType.Modify) AndAlso Object.ReferenceEquals(hhi.HandleObject, obj) Then
                    index = i
                    Exit For
                End If
            Next

            If index <> -1 Then
                _HistoryList(index).HandleObject = obj
            Else
                AddHandle(obj, HandleType.Modify)
            End If
        End Sub

        Public Sub Delete(ByVal obj As T)
            Dim index As Integer = -1
            For i As Integer = 0 To _HistoryList.Count - 1
                If _HistoryList(i).HandleType = HandleType.Create AndAlso Object.ReferenceEquals(_HistoryList(i).HandleObject, obj) Then
                    index = i
                    Exit For
                End If
            Next

            If index <> -1 Then
                _HistoryList.RemoveAt(index)
            Else
                AddHandle(obj, HandleType.Delete)
            End If
        End Sub

        Public Sub Clear()
            _HistoryList.Clear()
        End Sub

        Private Sub AddHandle(ByVal obj As T, ByVal type As HandleType)
            Dim item As New HistoryHandleItem(Of T)
            item.HandleObject = obj
            item.HandleType = type
            _HistoryList.Add(item)
        End Sub

    End Class

    Private Class HistoryHandleItem(Of T)

        Public HandleType As HandleType
        Public HandleObject As T

    End Class

    Private Enum HandleType
        Create = 1
        Modify = 2
        Delete = 4
    End Enum

#End Region

    Private Sub tsmiDetail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmiDetail.Click
        Detail()
    End Sub
End Class